const express = require('express');
const router = express.Router();
const { Dongtai, Hua } = require('../model/hua');
const { userModel } = require('../model/model');

// 获取动态列表 - 根据schoolId分类
router.get('/getDongtai', async (req, res) => {
  try {
    const { schoolId, userId } = req.query;

    // 如果没有提供schoolId，返回400错误
    if (!schoolId) {
      return res.status(400).json({ message: '请提供学校ID' });
    }

    // 根据schoolId过滤动态
    const dongtai = await Dongtai.find({ schoolId }).sort({ publishTime: -1 });

    // 为每个动态添加用户信息
    const enhancedDongtai = await Promise.all(
      dongtai.map(async (item) => {
        try {
          const user = await userModel.findById(item.userId);
          const itemObj = item.toObject();

          // 添加用户信息
          if (user) {
            itemObj.username = user.username;
            itemObj.avatarImage = user.avatarImage;
            itemObj.isAvatarImageSet = user.isAvatarImageSet;
          }

          return itemObj;
        } catch (error) {
          console.error(`获取用户信息失败: ${error.message}`);
          return item.toObject();
        }
      })
    );

    res.status(200).json(enhancedDongtai);
  } catch (error) {
    res.status(500).json({ message: '获取动态失败', error: error.message });
  }
})

// 发布动态
router.post('/publish', async (req, res) => {
  try {
    const { userId, huaId, schoolId, title, media } = req.body;

    // 验证必要参数
    if (!userId || !huaId || !schoolId || !title) {
      return res.status(400).json({ message: '用户ID、话题ID、学校ID和标题是必需的' });
    }

    // 创建新动态
    const newDongtai = new Dongtai({
      userId,
      huaId,
      schoolId,
      title,
      media: media || []
    });

    // 保存到数据库
    await newDongtai.save();
    res.status(201).json({ message: '发布成功', data: newDongtai });
  } catch (error) {
    res.status(500).json({ message: '发布失败', error: error.message });
  }
})

// 分享动态
router.post('/share', async (req, res) => {
  try {
    const { dongtaiId } = req.body;

    if (!dongtaiId) {
      return res.status(400).json({ message: '动态ID是必需的' });
    }

    const dongtai = await Dongtai.findById(dongtaiId);
    if (!dongtai) {
      return res.status(404).json({ message: '动态不存在' });
    }

    dongtai.shareCount = (dongtai.shareCount || 0) + 1;
    await dongtai.save();

    res.status(200).json({
      message: '分享成功',
      shareCount: dongtai.shareCount
    });
  } catch (error) {
    res.status(500).json({ message: '分享操作失败', error: error.message });
  }
})

// 评论点赞/取消点赞
router.post('/commentLike', async (req, res) => {
  try {
    const { commentId, like } = req.body;

    if (!commentId) {
      return res.status(400).json({ message: '评论ID是必需的' });
    }

    // 查找包含该评论的动态
    const dongtai = await Dongtai.findOne({ 'comments._id': commentId });
    if (!dongtai) {
      return res.status(404).json({ message: '找不到包含该评论的动态' });
    }

    // 查找评论
    const comment = dongtai.comments.id(commentId);
    if (!comment) {
      return res.status(404).json({ message: '评论不存在' });
    }

    // 更新点赞数量
    if (like) {
      comment.likeCount = (comment.likeCount || 0) + 1;
    } else {
      comment.likeCount = Math.max(0, (comment.likeCount || 0) - 1);
    }

    await dongtai.save();

    res.status(200).json({
      message: like ? '评论点赞成功' : '取消评论点赞成功',
      likeCount: comment.likeCount
    });
  } catch (error) {
    res.status(500).json({ message: '评论点赞操作失败', error: error.message });
  }
});

// 点赞/取消点赞动态
router.post('/like', async (req, res) => {
  try {
    const { dongtaiId, like } = req.body;

    if (!dongtaiId) {
      return res.status(400).json({ message: '动态ID是必需的' });
    }

    const dongtai = await Dongtai.findById(dongtaiId);
    if (!dongtai) {
      return res.status(404).json({ message: '动态不存在' });
    }

    // 更新点赞数量
    if (like) {
      dongtai.likeCount = (dongtai.likeCount || 0) + 1;
    } else {
      dongtai.likeCount = Math.max(0, (dongtai.likeCount || 0) - 1);
    }

    await dongtai.save();

    res.status(200).json({
      message: like ? '点赞成功' : '取消点赞成功',
      likeCount: dongtai.likeCount
    });
  } catch (error) {
    res.status(500).json({ message: '点赞操作失败', error: error.message });
  }
})

// 获取点赞状态
router.get('/getLikedStatus', async (req, res) => {
  try {
    const { userId, dongtaiIds } = req.query;

    if (!userId || !dongtaiIds) {
      return res.status(400).json({ message: '用户ID和动态ID列表是必需的' });
    }

    // 这里简化处理，实际项目中可能需要一个点赞集合来存储用户点赞记录
    // 为了演示，我们假设每个动态都有一个likedBy数组存储点赞用户ID
    const ids = dongtaiIds.split(',');
    const result = {};

    // 初始化所有动态ID的点赞状态为false
    ids.forEach(id => {
      result[id] = false;
    });

    // 在实际应用中，这里应该查询点赞集合
    // 由于当前模型中没有likedBy字段，我们返回所有false
    // 实际项目中需要添加这个字段并更新查询逻辑

    res.status(200).json(result);
  } catch (error) {
    res.status(500).json({ message: '获取点赞状态失败', error: error.message });
  }
})

// 评论动态
router.post('/comment', async (req, res) => {
  try {
    console.log('收到评论请求:', req.body);
    const { dongtaiId, content, userId, username } = req.body;

    if (!dongtaiId) {
      console.error('缺少动态ID');
      return res.status(400).json({ message: '缺少动态ID' });
    }
    if (!content) {
      console.error('缺少评论内容');
      return res.status(400).json({ message: '缺少评论内容' });
    }
    if (!userId) {
      console.error('缺少用户ID');
      return res.status(400).json({ message: '缺少用户ID' });
    }
    if (!username) {
      console.error('缺少用户名');
      return res.status(400).json({ message: '缺少用户名' });
    }

    console.log(`查找动态: ${dongtaiId}`);
    const dongtai = await Dongtai.findById(dongtaiId);
    if (!dongtai) {
      console.error(`动态不存在: ${dongtaiId}`);
      return res.status(404).json({ message: '动态不存在' });
    }
    console.log(`找到动态: ${dongtaiId}`);

    // 创建新评论对象
    const newComment = {
      userId,
      username,
      content,
      likeCount: 0,
      createdAt: new Date() // 手动添加创建时间
    };

    // 添加到评论数组
    dongtai.comments.push(newComment);
    // 更新评论数量
    dongtai.commentCount = dongtai.comments.length;

    // 先保存动态，确保评论已被保存到数据库
    console.log('保存动态...');
    await dongtai.save();
    console.log('动态保存成功');

    // 从数据库重新获取动态，确保数据最新
    const updatedDongtai = await Dongtai.findById(dongtaiId);
    if (!updatedDongtai) {
      console.error(`保存后无法找到动态: ${dongtaiId}`);
      return res.status(500).json({ message: '保存评论后无法找到动态' });
    }

    // 获取用户头像
    console.log(`查找用户: ${userId}`);
    const user = await userModel.findById(userId);
    if (!user) {
      console.error(`用户不存在: ${userId}`);
      // 用户不存在仍然允许评论，但没有头像
    } else {
      console.log(`找到用户: ${userId}`);
    }

    // 从更新后的动态中获取最新评论
    const savedComment = updatedDongtai.comments[updatedDongtai.comments.length - 1];
    if (!savedComment) {
      console.error('无法找到保存的评论');
      return res.status(500).json({ message: '无法找到保存的评论' });
    }
    console.log('找到保存的评论');

    // 创建带头像的评论对象
    const commentWithAvatar = {
      ...savedComment,
      avatarImage: user ? user.avatarImage : '',
      isAvatarImageSet: user ? user.isAvatarImageSet : false
    };

    // 确保createdAt存在并格式化
    if (commentWithAvatar.createdAt) {
      commentWithAvatar.createdAt = formatDate(commentWithAvatar.createdAt);
    } else {
      commentWithAvatar.createdAt = formatDate(new Date());
    }

    res.status(200).json({
      message: '评论成功',
      comment: commentWithAvatar,
      commentCount: dongtai.commentCount
    });
  } catch (error) {
    res.status(500).json({ message: '评论操作失败', error: error.message });
  }
})

// 用户关注/取消关注
router.post('/follow', async (req, res) => {
  try {
    const { followerId, followedId, follow } = req.body;

    if (!followerId || !followedId) {
      return res.status(400).json({ message: '关注者ID和被关注者ID是必需的' });
    }

    // 不能关注自己
    if (followerId === followedId) {
      return res.status(400).json({ message: '不能关注自己' });
    }

    // 查找关注者和被关注者
    const follower = await userModel.findById(followerId);
    const followed = await userModel.findById(followedId);

    if (!follower || !followed) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 检查是否已关注
    const isFollowing = follower.following.includes(followedId);

    // 执行关注/取消关注操作
    if (follow) {
      if (isFollowing) {
        return res.status(400).json({ message: '已经关注该用户' });
      }

      // 添加关注关系
      follower.following.push(followedId);
      followed.followers.push(followerId);
    } else {
      if (!isFollowing) {
        return res.status(400).json({ message: '未关注该用户' });
      }

      // 移除关注关系
      follower.following = follower.following.filter(id => id.toString() !== followedId);
      followed.followers = followed.followers.filter(id => id.toString() !== followerId);
    }

    // 保存更新
    await follower.save();
    await followed.save();

    // 更新关注数和粉丝数
    const followingCount = follower.following.length;
    const followersCount = followed.followers.length;

    res.status(200).json({
      message: follow ? '关注成功' : '取消关注成功',
      followingCount,
      followersCount
    });
  } catch (error) {
    res.status(500).json({ message: '关注操作失败', error: error.message });
  }
})

// 检查关注状态
router.get('/checkFollowing', async (req, res) => {
  try {
    const { followerId, followedId } = req.query;

    if (!followerId || !followedId) {
      return res.status(400).json({ message: '关注者ID和被关注者ID是必需的' });
    }

    // 查找关注者
    const follower = await userModel.findById(followerId);

    if (!follower) {
      return res.status(404).json({ message: '关注者不存在' });
    }

    // 检查是否已关注
    const isFollowing = follower.following.some(id => id.toString() === followedId);

    res.status(200).json({
      isFollowing
    });
  } catch (error) {
    res.status(500).json({ message: '检查关注状态失败', error: error.message });
  }
})

// 获取用户详情
router.get('/getUserDetail', async (req, res) => {
  try {
    const { userId } = req.query;

    if (!userId) {
      return res.status(400).json({ message: '请提供用户ID' });
    }

    const user = await userModel.findById(userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 获取用户发布的动态数量
    const dongtaiCount = await Dongtai.countDocuments({ userId });

    // 返回用户信息、动态数量、关注数和粉丝数
    res.status(200).json({
      userId: user._id,
      username: user.username,
      avatarImage: user.avatarImage,
      isAvatarImageSet: user.isAvatarImageSet,
      school: user.school,
      grade: user.grade,
      major: user.major,
      dongtaiCount,
      followingCount: user.following.length || 0,
      followersCount: user.followers.length || 0
    });
  } catch (error) {
    res.status(500).json({ message: '获取用户详情失败', error: error.message });
  }
})

// 获取用户动态列表
router.get('/getUserDongtai', async (req, res) => {
  try {
    const { userId } = req.query;

    if (!userId) {
      return res.status(400).json({ message: '请提供用户ID' });
    }

    // 根据userId查询用户发布的动态
    const dongtaiList = await Dongtai.find({ userId }).sort({ publishTime: -1 });

    // 为每个动态添加用户信息
    const enhancedDongtaiList = await Promise.all(
      dongtaiList.map(async (item) => {
        try {
          const user = await userModel.findById(item.userId);
          const itemObj = item.toObject();

          // 添加用户信息
          if (user) {
            itemObj.username = user.username;
            itemObj.avatarImage = user.avatarImage;
            itemObj.isAvatarImageSet = user.isAvatarImageSet;
          }

          return itemObj;
        } catch (error) {
          console.error(`获取用户信息失败: ${error.message}`);
          return item.toObject();
        }
      })
    );

    res.status(200).json(enhancedDongtaiList);
  } catch (error) {
    res.status(500).json({ message: '获取用户动态失败', error: error.message });
  }
})

// 获取动态详情
router.get('/getDongtaiDetail', async (req, res) => {
  try {
    const { id } = req.query;

    if (!id) {
      return res.status(400).json({ message: '动态ID是必需的' });
    }

    const dongtai = await Dongtai.findById(id);
    if (!dongtai) {
      return res.status(404).json({ message: '动态不存在' });
    }

    // 获取用户信息
    const user = await userModel.findById(dongtai.userId);
    const dongtaiObj = dongtai.toObject();

    if (user) {
      dongtaiObj.username = user.username;
      dongtaiObj.avatarImage = user.avatarImage;
      dongtaiObj.isAvatarImageSet = user.isAvatarImageSet;
    }

    res.status(200).json(dongtaiObj);
  } catch (error) {
    res.status(500).json({ message: '获取动态详情失败', error: error.message });
  }
})

// 获取关注用户的动态
router.get('/getFollowingDongtai', async (req, res) => {
  try {
    const { userId } = req.query;

    if (!userId) {
      return res.status(400).json({ message: '请提供用户ID' });
    }

    // 查找当前用户
    const user = await userModel.findById(userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 获取关注的用户ID列表
    const followingIds = user.following;
    if (!followingIds || followingIds.length === 0) {
      return res.status(200).json([]);
    }

    // 查找关注用户的动态
    const dongtaiList = await Dongtai.find({ userId: { $in: followingIds } })
      .sort({ publishTime: -1 });

    // 为每个动态添加用户信息
    const enhancedDongtaiList = await Promise.all(
      dongtaiList.map(async (item) => {
        try {
          const author = await userModel.findById(item.userId);
          const itemObj = item.toObject();

          // 添加用户信息
          if (author) {
            itemObj.username = author.username;
            itemObj.avatarImage = author.avatarImage;
            itemObj.isAvatarImageSet = author.isAvatarImageSet;
          }

          return itemObj;
        } catch (error) {
          console.error(`获取用户信息失败: ${error.message}`);
          return item.toObject();
        }
      })
    );

    res.status(200).json(enhancedDongtaiList);
  } catch (error) {
    res.status(500).json({ message: '获取关注用户动态失败', error: error.message });
  }
})

// 获取话题信息
router.get('/getTopicInfo', async (req, res) => {
  try {
    const { topicId } = req.query;

    if (!topicId) {
      return res.status(400).json({ message: '请提供话题ID' });
    }

    // 查询话题信息
    const topic = await Hua.findById(topicId);
    if (!topic) {
      return res.status(404).json({ message: '话题不存在' });
    }

    // 增加浏览量
    topic.viewCount += 1;
    await topic.save();

    res.status(200).json({
      _id: topic._id,
      name: topic.title,
      bannerImage: topic.img,
      description: topic.content,
      hot: topic.hot,
      viewCount: topic.viewCount
    });
  } catch (error) {
    res.status(500).json({ message: '获取话题信息失败', error: error.message });
  }
})

// 获取话题相关动态
router.get('/getTopicDongtais', async (req, res) => {
  try {
    const { topicId, type = 'hot' } = req.query;

    if (!topicId) {
      return res.status(400).json({ message: '请提供话题ID' });
    }

    // 根据话题ID查询动态
    let dongtaiList;
    if (type === 'hot') {
      // 热门动态按点赞数排序
      dongtaiList = await Dongtai.find({ huaId: topicId })
        .sort({ likeCount: -1, publishTime: -1 });
    } else {
      // 最新动态按发布时间排序
      dongtaiList = await Dongtai.find({ huaId: topicId })
        .sort({ publishTime: -1 });
    }

    // 为每个动态添加用户信息
    const enhancedDongtaiList = await Promise.all(
      dongtaiList.map(async (item) => {
        try {
          const user = await userModel.findById(item.userId);
          const itemObj = item.toObject();

          // 添加用户信息
          if (user) {
            itemObj.user = {
              _id: user._id,
              username: user.username,
              avatarImage: user.avatarImage,
              isAvatarImageSet: user.isAvatarImageSet
            };
          }

          return itemObj;
        } catch (error) {
          console.error(`获取用户信息失败: ${error.message}`);
          return item.toObject();
        }
      })
    );

    res.status(200).json(enhancedDongtaiList);
  } catch (error) {
    res.status(500).json({ message: '获取话题动态失败', error: error.message });
  }
})

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 获取动态评论
router.get('/getComments', async (req, res) => {
  try {
    const { dongtaiId } = req.query;

    if (!dongtaiId) {
      return res.status(400).json({ message: '动态ID是必需的' });
    }

    // 检查动态是否存在
    const dongtai = await Dongtai.findById(dongtaiId);
    if (!dongtai) {
      return res.status(404).json({ message: '动态不存在' });
    }

    // 获取评论并过滤掉用户1和用户2
    let comments = dongtai.comments
      .filter(comment => comment.username !== '用户1' && comment.username !== '用户2')
      .map(comment => ({
        ...comment.toObject(),
        createdAt: formatDate(comment.createdAt)
      }));

    // 按创建时间倒序排列
    comments.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

    // 获取每个评论用户的头像信息
    const commentsWithAvatar = await Promise.all(
      comments.map(async (comment) => {
        const user = await userModel.findById(comment.userId);
        return {
          ...comment,
          avatarImage: user ? user.avatarImage : '',
          isAvatarImageSet: user ? user.isAvatarImageSet : false
        };
      })
    );

    res.status(200).json(commentsWithAvatar);
  } catch (error) {
    res.status(500).json({ message: '获取评论失败', error: error.message });
  }
})

module.exports = router;